﻿using System;

namespace OS.Common.Utils
{
    /// <summary>
    /// 简单Ioc实例容器实现
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class IocContainer<T>
    {
        /// <summary>
        /// 具体实例创建者
        /// </summary>
        private static Func<T> _instanceCreater;

        /// <summary>
        /// 具体实例对象
        /// </summary>
        private static T _instance;

        /// <summary>
        /// 具体实例，根据设置时参数会返回具体单例还是新的实例
        /// </summary>
        public static T Instance
        {
            get
            {
                if (_instanceCreater == null)
                {
                    throw new Exception($"没有设置{typeof(T).Name}对应的映射类型！");
                }

                return _instanceCreater();
            }
        }

        /// <summary>
        /// 设置具体类型映射关系
        /// </summary>
        /// <typeparam name="TInstance">对象接口的实现类</typeparam>
        /// <param name="isSingle">是否是单例模式</param>
        public static void Set<TInstance>(bool isSingle = true) where TInstance : T, new()
        {
            if (_instanceCreater == null)
            {
                _instanceCreater = delegate
                {
                    if (isSingle)
                    {
                        return (T) (object) new TInstance();
                    }

                    if (_instance != null)
                    {
                        return _instance;
                    }

                    return _instance = (T) (object) new TInstance();
                };
            }
        }
    }
}